package com.rzico.quartz.job;

import com.rzico.basics.entity.Card;
import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.entity.Member;
import com.rzico.basics.service.CardService;
import com.rzico.basics.service.EnterpriseService;
import com.rzico.basics.service.MemberService;
import com.rzico.core.entity.SysJob;
import com.rzico.core.entity.SysPlugin;
import com.rzico.core.entity.SysTemplate;
import com.rzico.core.entity.SysUser;
import com.rzico.core.plugin.MsgPlugin;
import com.rzico.core.service.*;
import com.rzico.exception.CustomException;
import org.apache.commons.lang3.time.DateUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhongzm on 2020/2/2.
 * 计划任务执行demo
 */
public class CardExpireRemindTask implements Job {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    protected SysPvuvSummaryService sysPvuvSummaryService;

    @Autowired
    protected SysJobService sysJobService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    protected SysPluginService sysPluginService;

    @Autowired
    protected SysUserService sysUserService;

    @Autowired
    protected SysTemplateService sysTemplateService;

    @Autowired
    protected CardService cardService;

    @Autowired
    protected MemberService memberService;


    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String jobId = jobExecutionContext.getTrigger().getKey().getName();
        SysJob sysJob = sysJobService.selectByPrimaryKey(jobId);
        try {

            if (sysJob.getExecStatus().equals(1)) {
                //不能重复执行
                return;
            }
            sysJob.setExecStatus(1);
            sysJob.setJobDesc("开始执行:"+sdf.format(new Date()));
            sysJobService.updateByPrimaryKeySelective(sysJob);

            // 这里开始查询30分钟前未付款的订单，自动关闭, 20分钟定时查一次
            //   TODO

            String mchId = "";
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("name","葫芦派");
            List<Enterprise> enterpriseList= enterpriseService.selectList(param);
            if (0 < enterpriseList.size()) {
                mchId = enterpriseList.get(0).getMchId();
            }
            Map<String,Object> params = new HashMap<>();
            params.put("status",1);
            params.put("cardType",1);
            String searchRemindEndDate = com.rzico.util.DateUtils.getDateStr(DateUtils.addDays(new Date(),+3), com.rzico.util.DateUtils.HYPHEN_DISPLAY_DATE);
            params.put("searchRemindEndDate", searchRemindEndDate);
            List<Card> cardList = cardService.selectList(params);

            SysUser sysUser = null;
            //获取消息模块前要先获取用户
            String tplKey = "msg.cardRemind";
            SysPlugin sysPlugin = sysPluginService.getEnabledPlugin(mchId,SysPlugin.MSGPLUGIN);
            if (sysPlugin==null) {
                sysUser = sysUserService.findByUsername("admin");
                mchId = sysUser.getMchId();
                sysPlugin = sysPluginService.getEnabledPlugin(mchId,SysPlugin.MSGPLUGIN);
            }
            if (sysPlugin==null) {
                throw new CustomException("消息插件未安装");
            }
            SysTemplate template = sysTemplateService.findByTplKey(mchId,tplKey);
            if (null == template){
                sysUser = sysUserService.findByUsername("admin");
                mchId = sysUser.getMchId();
                template = sysTemplateService.findByTplKey(mchId,tplKey);
            }

            if (null == template) {
                throw new CustomException("消息模版不存在");
            }
            MsgPlugin msgPlugin = sysPluginService.getMsgPlugin(sysPlugin.getPluginId());

            for (Card card : cardList) {
                if (1 < card.getBalance().compareTo(new BigDecimal(5))) {
                    continue;
                }
                Map<String, Object> model = new HashMap<>();
                model.put("amount", card.getBalance());
                model.put("endDate", com.rzico.util.DateUtils.getDateStr(card.getEndDate(), com.rzico.util.DateUtils.HYPHEN_DISPLAY_DATE));
                String msg = sysTemplateService.encodeMsg(template, model);
                try {
                    msgPlugin.sendMsg(sysPlugin, memberService.selectByPrimaryKey(card.getMemberId()).getMobile(), msg);
                } catch (Exception e) {
                    throw new CustomException("发送消息出错");
                }
            }

            // end

            sysJob.setExecStatus(0);
            sysJob.setJobDesc("执行成功:"+sdf.format(new Date())+",下次执行:"+sdf.format(jobExecutionContext.getNextFireTime()));
            sysJobService.updateByPrimaryKeySelective(sysJob);
        }
        catch (Exception e) {
            sysJob.setExecStatus(0);
            sysJob.setJobDesc("执行错误:"+sdf.format(new Date()));
            sysJobService.updateByPrimaryKeySelective(sysJob);
        }

    }
}
